import React, { useEffect, useState } from 'react';
import { PageContainer, ProCard } from '@ant-design/pro-components';
import { Button, Descriptions } from 'antd';
import Tags from './tags'; // 假设 Tags 组件内部有一个 ProductDetails 组件  
import { getProductDetails, productNeedVerify, productVerifyPass, productVerifyUnpass } from '../../api/axios8081'; // 导入你的 API 函数 
import Operation from './Operation/operation'
import { record } from '../Manage/IssueTable'
import { useParams } from 'react-router-dom';
import ProductActionButton from '../Button/ProductActionButton'

export interface ProductDetails {
  name: string;
  imgUrl: string;
  describes: string;
  details: string;
  sendAddress: string;
  unsendAddress: string; 
  type: string;
  supplier: string;
  phoneNumber: string | number;
  server: any; // 最好明确类型  
  priceTypeList: Array<{
    priceType: number;
    score: number;
    money: number;
  }>;
}


const valueEnum = {
  '1': { text: '审核中' },
  '2': { text: '审核通过' },
  '3': { text: '审核失败' },
  '4': { text: '已上线' },
  '5': { text: '已下线' },
  '0': { text: '未审核' },
};

const Particulars: React.FC = () => {
  const [ProductVo, setProductVo] = useState<record | null>(null);
  const [productDetails, setProductDetails] = useState<ProductDetails | null>(null);

  const role = localStorage.getItem('role');
  console.log(role, 'role');


  const { Id } = useParams(); // 从useParams解构出id  
  let productId: string | undefined = Id;
  console.log(productId, '获取的id');

  const [isDataFetchedFromApi, setIsDataFetchedFromApi] = useState(false);
  useEffect(() => {
    // 尝试从localStorage获取数据    
    const selectedProductStr = localStorage.getItem('selectedProduct');
    if (selectedProductStr) {
      try {
        const selectedProduct: record = JSON.parse(selectedProductStr);
        setProductVo(selectedProduct);  
        console.log(selectedProduct, '这是什么')
      } catch (error) {
        console.error('解析localStorage中的数据出错:', error);
      }
    }
  }, []); //  



  const detailsProductVo = ProductVo;
  console.log(detailsProductVo, '这是detailsProductVo')


  useEffect(() => {
    const fetchData = async () => {
      try {
        if (!productId) {
          throw new Error('商品ID不能为空');
        }
        const response = await getProductDetails(productId);
        if (response) {
          setProductDetails(response);
          console.log(response, '这是response');
          setIsDataFetchedFromApi(true);
        } else {
          throw new Error(response.message);
        }
      } catch (error) {
        console.error('从接口获取商品具体信息失败:', error); // 打印完整的错误对象  
      }
    };
    fetchData();
  }, [productId]);

  const detailsToShow = productDetails;
  console.log(productDetails, '这是另一个');
  console.log(detailsToShow, '这是detailsToShow');
  const ButtonId = detailsProductVo?.id ?? '999999999999';
  const ButtonStatus = detailsProductVo?.status ?? 999999999999;
  const statusKey = ButtonStatus.toString() as keyof typeof valueEnum;
  const statusText = valueEnum[statusKey]?.text || '未知状态';
  //请求审核
  const handleRequestVerify = async () => {

    try {
      const response = await productNeedVerify(productId);
      // 处理响应，更新状态 
    } catch (error) {
      // 处理错误  
    }
  };
  //审核通过
  const handleVerifyPass = async () => {
    try {
      const response = await productVerifyPass(productId);
      // 处理响应，更新状态等  
    } catch (error) {
      // 处理错误  
    }
  };
  //审核不通过 
  const handleVerifyUnpass = async () => {
    try {
      const response = await productVerifyUnpass(productId);
      // 处理响应，更新状态等  
    } catch (error) {
      // 处理错误  
    }
  };


  return (
    <div style={{ background: '#F5F7FA' }}>
      <PageContainer
        ghost
        header={{
          title: detailsProductVo?.name,
          breadcrumb: {},
        }}

        extra={[
          // ... 你的按钮  
          <Button key="3">编辑</Button>,
          role === '1' && <Button type="primary" key="request-verify" onClick={handleRequestVerify}>发起审核</Button>,
          role === '0' && <Button type="primary" key="verify-pass" onClick={handleVerifyPass}>审核通过</Button>,
          role === '0' && <Button type="primary" key="verify-unpass" onClick={handleVerifyUnpass}>审核驳回</Button>,
          <ProductActionButton productId={ButtonId} status={ButtonStatus} />
        ]}
        content={
          <Descriptions column={2} style={{ marginBlockEnd: -16 }}>
            <Descriptions.Item label="管理人">{detailsProductVo?.adminUser}</Descriptions.Item>

            <Descriptions.Item label="权益id">{detailsProductVo?.id}</Descriptions.Item>
            <Descriptions.Item label="状态"> {statusText} </Descriptions.Item>
          </Descriptions>
        }
      >
        <ProCard direction="column" ghost gutter={[0, 16]}>
          {detailsToShow && (
            <ProCard >
              <Tags productDetails={detailsToShow} /> 
            </ProCard>
          )}

          <ProCard>
            <Operation productId={productId!} />
          </ProCard>
        </ProCard>
      </PageContainer>
    </div>
  );
};

export default Particulars;